<template>
  <div>
    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="page-title">热门关键词</div>

      <!-- 关键词筛选 -->
      <div class="keyword-filter">
        <div class="filter-group">
          <div class="filter-title">分类：</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'all' }"
            @click="setCategory('all')"
          >全部</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'fashion' }"
            @click="setCategory('fashion')"
          >时尚</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'beauty' }"
            @click="setCategory('beauty')"
          >美妆</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'food' }"
            @click="setCategory('food')"
          >美食</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'travel' }"
            @click="setCategory('travel')"
          >旅行</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'lifestyle' }"
            @click="setCategory('lifestyle')"
          >生活方式</div>
          <div
            class="filter-tag"
            :class="{ 'active': categoryFilter === 'tech' }"
            @click="setCategory('tech')"
          >科技</div>
        </div>

        <div class="filter-group">
          <div class="filter-title">时间：</div>
          <div
            class="filter-tag"
            :class="{ 'active': timeFilter === 'day' }"
            @click="setTime('day')"
          >今日</div>
          <div
            class="filter-tag"
            :class="{ 'active': timeFilter === 'week' }"
            @click="setTime('week')"
          >本周</div>
          <div
            class="filter-tag"
            :class="{ 'active': timeFilter === 'month' }"
            @click="setTime('month')"
          >本月</div>
        </div>

        <div class="filter-group">
          <div class="filter-title">热度：</div>
          <div
            class="filter-tag"
            :class="{ 'active': hotFilter === 'all' }"
            @click="setHot('all')"
          >全部</div>
          <div
            class="filter-tag"
            :class="{ 'active': hotFilter === 'rising' }"
            @click="setHot('rising')"
          >上升最快</div>
          <div
            class="filter-tag"
            :class="{ 'active': hotFilter === 'top' }"
            @click="setHot('top')"
          >热度最高</div>
          <div
            class="filter-tag"
            :class="{ 'active': hotFilter === 'new' }"
            @click="setHot('new')"
          >最新出现</div>
        </div>
      </div>

      <!-- 关键词趋势 -->
      <div class="keyword-trend">
        <div class="trend-header">
          <div class="trend-title">热门关键词趋势</div>
          <div class="trend-tabs">
            <div
              class="trend-tab"
              :class="{ 'active': trendTab === 'overall' }"
              @click="setTrendTab('overall')"
            >总体趋势</div>
            <div
              class="trend-tab"
              :class="{ 'active': trendTab === 'fashion' }"
              @click="setTrendTab('fashion')"
            >时尚</div>
            <div
              class="trend-tab"
              :class="{ 'active': trendTab === 'beauty' }"
              @click="setTrendTab('beauty')"
            >美妆</div>
            <div
              class="trend-tab"
              :class="{ 'active': trendTab === 'food' }"
              @click="setTrendTab('food')"
            >美食</div>
          </div>
        </div>

        <div class="keyword-list">
          <div
            class="keyword-card"
            v-for="(keyword, index) in filteredKeywords"
            :key="keyword.id"
          >
            <div class="keyword-header">
              <div class="keyword-text">{{ keyword.text }}</div>
              <div
                class="keyword-rank"
                :class="{ 'top3': index < 3 }"
              >{{ index + 1 }}</div>
            </div>

            <div class="keyword-metrics">
              <div>
                <i class="fa-solid fa-eye keyword-trend-icon"></i>
                {{ keyword.views | numberFormat }}
              </div>
              <div>
                <i class="fa-solid fa-arrow-up keyword-trend-icon up"></i>
                {{ keyword.growthRate }}%
              </div>
              <div>
                <i class="fa-solid fa-calendar-day"></i>
                {{ keyword.updatedAt }}
              </div>
            </div>

            <div class="keyword-details">
              <div class="detail-item">
                <div class="detail-label">相关笔记</div>
                <div class="detail-value">{{ keyword.notes | numberFormat }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">互动量</div>
                <div class="detail-value">{{ keyword.interactions | numberFormat }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">竞争指数</div>
                <div class="detail-value">{{ keyword.competition }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-4 text-center">
          <el-button type="text" @click="loadMore">加载更多</el-button>
        </div>
      </div>

      <!-- 关键词分析图表 -->
      <div class="keyword-chart">
        <div class="trend-header">
          <div class="trend-title">热门关键词趋势分析</div>
          <div class="chart-actions">
            <el-select v-model="chartTimeRange" placeholder="选择时间范围" size="small">
              <el-option label="近7天" value="7d"></el-option>
              <el-option label="近30天" value="30d"></el-option>
              <el-option label="近90天" value="90d"></el-option>
            </el-select>
          </div>
        </div>

        <div class="chart-container">
          <canvas id="keywordChart"></canvas>
        </div>
      </div>

      <!-- 相关推荐 -->
      <div class="related-keywords">
        <div class="trend-title">相关推荐关键词</div>

        <div class="related-list">
          <div
            class="related-tag"
            v-for="tag in relatedTags"
            :key="tag"
          >{{ tag }}</div>
        </div>
      </div>
    </div>

    <!-- 关键词详情弹窗 -->
    <el-dialog v-model="keywordDetailVisible" title="关键词详情">
      <template #content>
        <div class="detail-content">
          <div class="detail-header">
            <div class="detail-title">{{ currentKeyword.text }}</div>
            <div class="detail-metrics">
              <div class="metric-item">
                <div class="metric-value">{{ currentKeyword.views | numberFormat }}</div>
                <div class="metric-label">浏览量</div>
              </div>
              <div class="metric-item">
                <div class="metric-value">{{ currentKeyword.notes | numberFormat }}</div>
                <div class="metric-label">相关笔记</div>
              </div>
              <div class="metric-item">
                <div class="metric-value">{{ currentKeyword.interactions | numberFormat }}</div>
                <div class="metric-label">互动量</div>
              </div>
              <div class="metric-item">
                <div class="metric-value">{{ currentKeyword.competition }}</div>
                <div class="metric-label">竞争指数</div>
              </div>
            </div>
          </div>

          <div class="detail-chart">
            <canvas id="detailChart"></canvas>
          </div>

          <div class="detail-related">
            <div class="related-title">相关热门内容</div>
            <div class="related-content">
              <div
                class="content-item"
                v-for="(item, index) in relatedContents"
                :key="index"
              >
                <div class="content-thumbnail">
                  <img :src="item.thumbnail" alt="内容缩略图">
                </div>
                <div class="content-info">
                  <div class="content-title">{{ item.title }}</div>
                  <div class="content-meta">
                    <div class="content-author">
                      <img :src="item.author.avatar" alt="作者头像" class="author-avatar">
                      <span>{{ item.author.name }}</span>
                    </div>
                    <div class="content-stats">
                      <span><i class="fa-solid fa-eye"></i> {{ item.views | numberFormat }}</span>
                      <span><i class="fa-solid fa-heart"></i> {{ item.likes | numberFormat }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="keywordDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="useKeyword">使用关键词</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
   name: "trending-View",
  data() {
    return {
      activeMenu: 'keywords-trending',
      categoryFilter: 'all',
      timeFilter: 'week',
      hotFilter: 'all',
      trendTab: 'overall',
      chartTimeRange: '30d',
      keywords: [],
      relatedTags: [],
      keywordDetailVisible: false,
      currentKeyword: {},
      relatedContents: [],
      // 假设每页加载 10 条数据
      pageSize: 10,
      currentPage: 1
    };
  },
  computed: {
    filteredKeywords() {
      // 这里需要实现实际的筛选逻辑
      // 示例：根据分类、时间、热度筛选关键词
      return this.keywords
        .filter(keyword => {
          if (this.categoryFilter === 'all') return true;
          return keyword.category === this.categoryFilter;
        })
        .filter(keyword => {
          if (this.timeFilter === 'day') {
            return this.isWithinLastDay(keyword.updatedAt);
          } else if (this.timeFilter === 'week') {
            return this.isWithinLastWeek(keyword.updatedAt);
          } else if (this.timeFilter === 'month') {
            return this.isWithinLastMonth(keyword.updatedAt);
          }
          return true;
        })
        .filter(keyword => {
          if (this.hotFilter === 'all') return true;
          if (this.hotFilter === 'rising') {
            return keyword.growthRate > 10; // 假设增长率大于 10% 为上升最快
          }
          if (this.hotFilter === 'top') {
            return keyword.views > 10000; // 假设浏览量大于 10000 为热度最高
          }
          if (this.hotFilter === 'new') {
            return this.isNewKeyword(keyword.updatedAt);
          }
          return true;
        })
        .slice(0, this.currentPage * this.pageSize);
    }
  },
  filters: {
    numberFormat(value) {
      if (!value) return '0';

      if (value >= 10000) {
        return (value / 10000).toFixed(1) + 'w';
      }

      return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
  },
  methods: {
    handleOpen() {
      // 处理侧边栏菜单展开事件
    },
    handleClose() {
      // 处理侧边栏菜单关闭事件
    },
    setCategory(category) {
      this.categoryFilter = category;
      this.currentPage = 1;
    },
    setTime(time) {
      this.timeFilter = time;
      this.currentPage = 1;
    },
    setHot(hot) {
      this.hotFilter = hot;
      this.currentPage = 1;
    },
    setTrendTab(tab) {
      this.trendTab = tab;
      // 切换标签时重新加载数据
      this.loadKeywords();
    },
    loadKeywords() {
      // 这里需要实现实际的加载关键词数据的逻辑
      // 示例：使用 axios 获取数据
      // axios.get('/api/keywords', {
      //   params: {
      //     category: this.categoryFilter,
      //     time: this.timeFilter,
      //     hot: this.hotFilter
      //   }
      // }).then(response => {
      //   this.keywords = response.data;
      //   this.renderChart();
      // });
    },
    loadMore() {
      this.currentPage++;
    },
    renderChart() {
      // 这里需要实现实际的绘制图表的逻辑
      if (this.keywordChart) {
        this.keywordChart.destroy();
      }
      const ctx = document.getElementById('keywordChart').getContext('2d');
      this.keywordChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          datasets: [{
            label: '热门关键词趋势',
            data: [12, 19, 3, 5, 2, 3, 10],
            borderColor: '#FE2C55',
            fill: false
          }]
        },
        options: {
          responsive: true
        }
      });
    },
    isWithinLastDay(date) {
      const now = new Date();
      const target = new Date(date);
      const diffTime = Math.abs(now - target);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays <= 1;
    },
    isWithinLastWeek(date) {
      const now = new Date();
      const target = new Date(date);
      const diffTime = Math.abs(now - target);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays <= 7;
    },
    isWithinLastMonth(date) {
      const now = new Date();
      const target = new Date(date);
      const diffMonths = (now.getFullYear() - target.getFullYear()) * 12 + (now.getMonth() - target.getMonth());
      return diffMonths === 0;
    },
    isNewKeyword(date) {
      const now = new Date();
      const target = new Date(date);
      const diffDays = Math.ceil((now - target) / (1000 * 60 * 60 * 24));
      return diffDays <= 3; // 假设 3 天内为新关键词
    },
    showKeywordDetail(keyword) {
      this.currentKeyword = keyword;
      this.keywordDetailVisible = true;
      // 加载相关内容
      // axios.get(`/api/related-contents/${keyword.id}`).then(response => {
      //   this.relatedContents = response.data;
      // });
      // 绘制详情图表
      this.renderDetailChart();
    },
    renderDetailChart() {
      if (this.detailChart) {
        this.detailChart.destroy();
      }
      const ctx = document.getElementById('detailChart').getContext('2d');
      this.detailChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['浏览量', '相关笔记', '互动量', '竞争指数'],
          datasets: [{
            label: '关键词详情',
            data: [
              this.currentKeyword.views,
              this.currentKeyword.notes,
              this.currentKeyword.interactions,
              this.currentKeyword.competition
            ],
            backgroundColor: [
              'rgba(254, 44, 85, 0.8)',
              'rgba(76, 217, 100, 0.8)',
              'rgba(51, 153, 255, 0.8)',
              'rgba(255, 149, 0, 0.8)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    },
    useKeyword() {
      // 实现使用关键词的逻辑
      this.keywordDetailVisible = false;
    }
  },
  mounted() {
    this.loadKeywords();
    this.renderChart();
  }
};
</script>

<style scoped lang="scss">

    /* 热门关键词相关样式 */
    .keyword-filter {
      background-color: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
      margin-bottom: 20px;
    }
    
    .filter-group {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 15px;
    }
    
    .filter-title {
      font-weight: 500;
      margin-right: 10px;
      margin-bottom: 5px;
    }
    
    .filter-tag {
      padding: 6px 12px;
      border-radius: 16px;
      cursor: pointer;
      transition: all 0.3s ease;
    }
    
    .filter-tag:hover {
      background-color: rgba(254, 44, 85, 0.1);
    }
    
    .filter-tag.active {
      background-color: rgba(254, 44, 85, 0.2);
      color: var(--primary-color);
      font-weight: 500;
    }
    
    .keyword-trend {
      background-color: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
      margin-bottom: 20px;
    }
    
    .trend-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
    }
    
    .trend-tabs {
      display: flex;
      gap: 15px;
    }
    
    .trend-tab {
      padding: 8px 16px;
      border-radius: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
    }
    
    .trend-tab:hover {
      background-color: rgba(254, 44, 85, 0.1);
    }
    
    .trend-tab.active {
      background-color: var(--primary-color);
      color: white;
    }
    
    .keyword-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 16px;
    }
    
    .keyword-card {
      padding: 16px;
      border-radius: 12px;
      border: 1px solid #EBEEF5;
      transition: all 0.3s ease;
      cursor: pointer;
    }
    
    .keyword-card:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }
    
    .keyword-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    
    .keyword-text {
      font-size: 16px;
      font-weight: 500;
    }
    
    .keyword-rank {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background-color: rgba(254, 44, 85, 0.1);
      color: var(--primary-color);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      font-weight: 500;
    }
    
    .keyword-rank.top3 {
      background-color: var(--primary-color);
      color: white;
    }
    
    .keyword-metrics {
      display: flex;
      gap: 15px;
      color: var(--gray-color);
      font-size: 14px;
    }
    
    .keyword-trend-icon {
      margin-right: 5px;
    }
    
    .keyword-trend-icon.up {
      color: #FF4D4F;
    }
    
    .keyword-trend-icon.down {
      color: #4CD964;
    }
    
    .keyword-details {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #EBEEF5;
    }
    
    .detail-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      font-size: 14px;
    }
    
    .detail-label {
      color: var(--gray-color);
    }
    
    .detail-value {
      font-weight: 500;
    }
    
    /* 关键词分析图表 */
    .keyword-chart {
      background-color: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
      margin-bottom: 20px;
    }
    
    .chart-container {
      height: 300px;
    }
    
    /* 相关推荐 */
    .related-keywords {
      background-color: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    
    .related-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
    
    .related-tag {
      padding: 8px 16px;
      background-color: #F8F8F8;
      border-radius: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
    }
    
    .related-tag:hover {
      background-color: rgba(254, 44, 85, 0.1);
      color: var(--primary-color);
    }
</style>
